package org.android.application.marksixmanage.activity;

import android.app.AlertDialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.*;
import cn.bmob.BmobException;
import cn.bmob.BmobQuery;
import cn.bmob.SaveCallback;
import org.android.application.marksixmanage.R;
import org.android.application.marksixmanage.dao.ResultDataDao;
import org.android.application.marksixmanage.grab.GrabAbstract;
import org.android.application.marksixmanage.grab.LotterySixGrab;
import org.android.application.marksixmanage.model.LotteryPlatform;
import org.android.application.marksixmanage.model.LotteryResult;

import java.util.ArrayList;
import java.util.List;

public class UploadResultActivity extends BaseActivity implements
		OnClickListener {

	private Spinner sp_platform;
	private Button btn_grab;
	private Button btn_submit;
	private Button btn_modif;
	private EditText edt_result;
	private EditText edt_issueNumber;
	private ListView view_query;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_upload);
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
		sp_platform = (Spinner) findViewById(R.id_upload.spinner_platform);
		sp_platform.setAdapter(new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, LotteryPlatform
						.getLotteryItems()));
		btn_grab = (Button) findViewById(R.id_upload.btn_grab);
		btn_grab.setOnClickListener(this);
		btn_submit = (Button) findViewById(R.id_upload.btn_submit);
		btn_submit.setOnClickListener(this);

		btn_modif = (Button) findViewById(R.id_upload.btn_modif);
		btn_modif.setOnClickListener(this);

		edt_result = (EditText) findViewById(R.id_upload.edt_result);
		edt_issueNumber = (EditText) findViewById(R.id_upload.edt_issue);
		
		//view_query = (ListView) findViewById(R.id_upload.listView_query);
		

		//view_query.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1,queryResults()));

        //setContentView(view_query);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id_upload.btn_grab:
			LotteryResult resultData = grabResult();
			if (resultData == null) {
				new AlertDialog.Builder(this).setMessage("没有查找到当期彩果")
						.setPositiveButton("Ok", null).show();
				break;
			}
			edt_result.setText(resultData.getResultData());
			break;
		case R.id_upload.btn_submit:
			submitData();
			break;
		case R.id_upload.btn_modif:
			submitData();
			break;
		default:
			break;
		}
	}

	private LotteryResult grabResult() {
		LotteryResult resultData = null;
		String platformString = sp_platform.getSelectedItem().toString();
		GrabAbstract grabUtil = null;
		if (platformString.equals(LotteryPlatform.Lottery_SiX.getLotteryName())) {
			grabUtil = new LotterySixGrab();
		}
		String url = "http://www.mingpaoracing.com/mpmark6/cfm/main_01.cfm";
		String encode = "big5";
		String issueNumber = edt_issueNumber.getText().toString();
		if (grabUtil != null) {
			resultData = grabUtil.grabData(url, encode, issueNumber);
		}
		if (resultData != null) {
			resultData.setPlatformId(LotteryPlatform.getLotteryPlatformByName(
					platformString).getPlatformId());
		}
		return resultData;
	}


	private void submitData() {
		try {

			LotteryResult data = null;
			ResultDataDao dao = new ResultDataDao();
			
			BmobQuery query = dao.getBmobQuery();

			Integer platformId = LotteryPlatform.getLotteryPlatformByName(
					sp_platform.getSelectedItem().toString()).getPlatformId();

			query.whereEqualTo(LotteryResult.FN_ISSUENUMBER, edt_issueNumber.getText().toString());
			query.whereEqualTo(LotteryResult.FN_PLATFORMID, platformId);

			List<LotteryResult> results = dao.query(query);
			if(results!=null&&!results.isEmpty()){
				data = results.get(0);
			}else{
				data = new LotteryResult();
			}

			data.setPlatformId(platformId);
			data.setResultData(edt_result.getText().toString());
			data.setIssueNumber(edt_issueNumber.getText().toString());

			SaveCallback callback = new SaveCallback() {
				@Override
				public void done(BmobException arg0) {
					new AlertDialog.Builder(UploadResultActivity.this)
							.setMessage("操作成功").setPositiveButton("Ok", null)
							.show();
				}
			};
			if(data.getObjectId()!=null){
				dao.updateInBackgound(data, callback);
			}else{
				dao.saveInBackground(data, callback);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	private List<String> queryResults(){
		ResultDataDao dao = new ResultDataDao();
		BmobQuery  query = dao.getBmobQuery();
		//query.whereEqualTo(LotteryResult.FN_PLATFORMID, LotteryPlatform.getLotteryPlatformByName(sp_platform.getSelectedItem().toString()).getPlatformId());
		try {
			List<LotteryResult> resultList = dao.query(query);
			List<String> resultStrings = new ArrayList<String>();
			for(LotteryResult result:resultList){
				String reString  = LotteryPlatform.getLotteryPlatformById(result.getPlatformId())+"      "+result.getIssueNumber()+"       "+result.getResultData();
				resultStrings.add(reString);
			}
			return resultStrings;
		} catch (BmobException e) {
			e.printStackTrace();
		}
		return null;
	}
}
